﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AMS.DD35.DbAccess.SqlClient
{
    public class SqlEDMRegisterConnector : IRegisterConnector
    {
        public SqlEDMRegisterConnector()
        { }

        public bool UsernameExists(string username)
        {
            using (DD35DataEntities dbContext = new DD35DataEntities())
            {
                User user;
                try
                {
                    //user = dbContext.Users.Single(u => u.Username == username); // throws IOE
                    //user = dbContext.Users.First(u => u.Username == username); // throws IOE
                    user = dbContext.Users.FirstOrDefault(u => u.Username == username); // returns null
                    //user = dbContext.Users.Find(u.Username); // ??
                }
                catch (InvalidOperationException)
                {
                    return false;
                }
                return user != null;
            }
        }

        public void InsertUserInfo(string username, string passwordHash, string email)
        {
            User user = User.CreateUser(username, passwordHash, email);
            using (DD35DataEntities dbContext = new DD35DataEntities())
            {
                dbContext.AddToUsers(user);
                dbContext.SaveChanges();
            }
        }
    }
}
